import 'package:collection/collection.dart';
import 'package:get/get.dart';
import 'package:squat_easy/se_db/se_db_database.dart';
import 'package:squat_easy/se_db/se_db_entity.dart';
import 'package:squat_easy/se_main/se_home/se_home_logic.dart';
import 'package:squat_easy/se_service/se_user_service.dart';

class SeRecentRunLogic extends GetxController {
  List<GroupedTraining> list = [];

  @override
  void onReady() async {
    super.onReady();

    list = await fetchGroupedTrainings();
    update();
  }

  ///获取所有训练数据并按日期分组
  Future<List<GroupedTraining>> fetchGroupedTrainings() async {
    final database = await $FloorSeAppDatabase.databaseBuilder(SeDbConstant.databaseName).build();
    final dao = database.trainingDao;

    final allTrainings = await dao.findTrainingByUserId(SeUserService.instance.userId);

    final grouped = groupBy(allTrainings, (Training training) => training.createTime);

    return grouped.entries.map((entry) {
      return GroupedTraining(
        groupDate: entry.key,
        trainings: entry.value,
      );
    }).toList();
  }
}
